package com.roamer.school.web.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;
import com.roamer.school.repository.entity.sys.SysUser;
import com.roamer.school.shiro.util.ShiroUtils;
import com.roamer.school.web.handler.ControllerExceptionHandler;
import com.roamer.school.web.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;

/**
 * Log切面处理
 *
 * @author roamer
 * @version V1.0
 * @date 2019/1/20 19:29
 */
@Aspect
@Component
@Slf4j
public class LoggerAspect {

    private static final ObjectMapper mapper = new ObjectMapper();

    private static final String SHORT_METHOD_NAME_SUFFIX = "(..)";

    @Pointcut(
            "@within(org.springframework.web.bind.annotation.RestController) || @annotation(org.springframework.web.bind.annotation.RestController)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object apiLog(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        boolean logFlag = this.needToLog(method);
        if (!logFlag) {
            return joinPoint.proceed();
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        Optional<SysUser> loginUser = ShiroUtils.getCurrentUser();
        String ip = IpUtils.getRealIp(request);
        String methodName = this.getMethodName(joinPoint);
        String params = this.getParamsJson(joinPoint);
        String requester = loginUser.isPresent() ? String.valueOf(loginUser.get().getId()) : IpUtils.UNKNOWN_ADDR;

        //        String callSource = request.getHeader(HeaderConstants.CALL_SOURCE);
        //        String appVersion = request.getHeader(HeaderConstants.APP_VERSION);
        //        String apiVersion = request.getHeader(HeaderConstants.API_VERSION);
        String userAgent = request.getHeader("user-agent");

        log.info("Started request requester [{}] method [{}] params [{}] IP [{}]  userAgent [{}]", requester,
                 methodName, params, ip, userAgent);
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        log.info("Ended request requester [{}] method [{}] params[{}] response is [{}] cost [{}] millis ", requester,
                 methodName, params, this.deleteSensitiveContent(result), System.currentTimeMillis() - start);
        return result;
    }

    /**
     * 获取目标函数名
     *
     * @param joinPoint 切点
     *
     * @return {@code String}  目标函数名
     */
    private String getMethodName(ProceedingJoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().toShortString();
        if (methodName.endsWith(SHORT_METHOD_NAME_SUFFIX)) {
            methodName = methodName.substring(0, methodName.length() - SHORT_METHOD_NAME_SUFFIX.length());
        }
        return methodName;
    }

    /**
     * 获取目标函数参数
     *
     * @param joinPoint 切点
     *
     * @return {@code String} 目标函数参数
     */
    private String getParamsJson(ProceedingJoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        StringBuilder sb = new StringBuilder();
        for (Object arg : args) {
            //移除敏感内容
            String paramStr;
            if (arg instanceof HttpServletResponse) {
                paramStr = HttpServletResponse.class.getSimpleName();
            } else if (arg instanceof HttpServletRequest) {
                paramStr = HttpServletRequest.class.getSimpleName();
            } else if (arg instanceof MultipartFile) {
                long size = ((MultipartFile) arg).getSize();
                paramStr = MultipartFile.class.getSimpleName() + " size:" + size;
            } else {
                paramStr = this.deleteSensitiveContent(arg);
            }
            sb.append(paramStr).append(",");
        }
        return sb.toString();
    }

    /**
     * 判断是否需要记录日志
     *
     * @param method 目标函数
     *
     * @return {@code true} GetMapping和已被全局异常处理的不再打印日志,
     */
    private boolean needToLog(Method method) {
        return /*method.getAnnotation(GetMapping.class) == null &&*/ !method.getDeclaringClass()
                                                                            .equals(ControllerExceptionHandler.class);
    }

    /**
     * 删除参数中的敏感内容
     *
     * @param obj 参数对象
     *
     * @return {@code String} 脱敏后的数据
     */
    private String deleteSensitiveContent(Object obj) {
        JsonNode node = null;
        try {
            if (obj instanceof Exception) {
                return mapper.writeValueAsString(obj);
            }

            String param = mapper.writeValueAsString(obj);
            node = mapper.readTree(param);
            List<String> sensitiveFieldList = this.getSensitiveFieldList();
            for (String sensitiveField : sensitiveFieldList) {
                if (node.has(sensitiveField)) {
                    ((ObjectNode) node).put(sensitiveField, "******");
                }
            }

        } catch (JsonProcessingException e) {
            return String.valueOf(obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return String.valueOf(node);
    }

    /**
     * 敏感字段列表
     *
     * @return {@code List<String>} 字段列表
     */
    private List<String> getSensitiveFieldList() {
        List<String> sensitiveFieldList = Lists.newArrayList();
        sensitiveFieldList.add("pwd");
        sensitiveFieldList.add("password");
        return sensitiveFieldList;
    }
}
